package com.netty.bfport.netty.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.stereotype.Component;

/**
 * @Author: zhaoyang05
 * @Data: 2022/3/2 15:50
 * @Description
 * 心跳监听
 */
@Component
@ChannelHandler.Sharable
public class ServerIdleStateTrigger extends ChannelInboundHandlerAdapter {

    /**
     * 规定时间内未收到客户端任何数据包，将猪冻断开连接
     * evt这个数据是用户
     * */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                // 在规定时间内没有收到客户端的上行数据, 主动断开连接
                ctx.disconnect();
                Channel channel = NettyServerHandler.channelsApp.find(ctx.channel().id());
                if (channel==null){
                    Channel channel1 = NettyServerHandler.channelsWeb.find(ctx.channel().id());
                    NettyServerHandler.channelsWeb.remove(channel1);
                }else {
                    NettyServerHandler.channelsApp.remove(channel);
                    NettyServerHandler.message.remove(ctx.channel().id().toString());
                }
            }
        } else {
            ctx.writeAndFlush("ok");
            super.userEventTriggered(ctx, evt);
        }
    }
}
